package eu.boss;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ObjectMapper;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;

import eu.boss.model.Player;
import eu.boss.model.StatsMessage;
import eu.boss.model.Team;

public class LoginServlet extends HttpServlet {

	private static final long serialVersionUID = 486069541828513649L;
	private DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		StatsMessage statsMsg = new StatsMessage("");

		String hash = req.getParameter("hash");
		boolean isValid=false;	
		resp.setContentType("text/plain");
		
		if (hash!=null){
		
			Query query = new Query("UserList");
			for (Entity entity : datastore.prepare(query).asIterable()) {
				String id= String.valueOf(entity.getProperty("hash"));
				if (id.compareTo(hash)==0)
					isValid=true;
			}
	
			if (!isValid)
				resp.getWriter().println("LOGIN ERROR");
				
			else{		
				
				//Returns playerList
				ObjectMapper mapper = new ObjectMapper();
				
				// searching for entity "Players"
				Query q = new Query("PlayerList" + hash);
				PreparedQuery pq = datastore.prepare(q);
				for (Entity result : pq.asIterable()) {
					String playerList = (String) result.getProperty("playerList");
					statsMsg.getPlayers().add(mapper.readValue(playerList, Player.class));
				}
			
				// searching for entity "teamList"
				q = new Query("TeamList" + hash);
				pq = datastore.prepare(q);
				boolean isClear=false;
				for (Entity result : pq.asIterable()) {
					if (!isClear){
						statsMsg.getTeams().clear();
						isClear=true;
					}
					String teamList = (String) result.getProperty("teamList");
					statsMsg.getTeams().add(mapper.readValue(teamList, Team.class));
				}

				
				
				// displaying response
				resp.setContentType("text/plain");
				resp.getWriter().println(mapper.writeValueAsString(statsMsg));
			}
		}
		else
			resp.getWriter().println("LOGIN ERROR");
	}
}
